package com.nw.filer;

import com.alibaba.fastjson.JSONObject;
import com.nw.common.Result;
import com.nw.enums.ReturnStatusEnum;
import com.nw.enums.ValidateReturnCodeEnum;
import com.nw.utils.IpAdrressUtil;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;

/**
 * 1.@Component就是把这个类注入到IOC容器中
 2.@WebFilter(urlPatterns = "/Blogs",filterName = "blosTest")说明这是一个web过滤器，它拦截的url为/Blogs，过滤器名字为blogsTest
 */
@Component
@WebFilter(urlPatterns = "/mongoJson",filterName = "blosTest")
public class TestFilter implements Filter{


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request= (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        System.out.printf("过滤器实现");
        String ip = IpAdrressUtil.getIpAdrress(request);
        if(ip.contains("127.0.0.1") ||ip.contains("0:0:0:0:0:0:0:1")){
            filterChain.doFilter(request,response);
        }else{
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            request.setAttribute("","");
            PrintWriter out = null ;
            /*Result result = new Result();
            result.setStatus(ReturnStatusEnum.FAILURE.getCode());
            result.setMsg(ReturnStatusEnum.FAILURE.getDesc());
            result.setReturnCode(ValidateReturnCodeEnum.USER_VALID_URL_IP_FAILURE.getCode());
            result.setReturnMsg(ValidateReturnCodeEnum.USER_VALID_URL_IP_FAILURE.getDesc());*/
            JSONObject res = new JSONObject();
            res.put("status",ReturnStatusEnum.FAILURE.getCode());
            res.put("msg",ReturnStatusEnum.FAILURE.getDesc());
            res.put("returnCode",ValidateReturnCodeEnum.USER_VALID_URL_IP_FAILURE.getCode());
            res.put("returnMsg",ValidateReturnCodeEnum.USER_VALID_URL_IP_FAILURE.getDesc());
            out = response.getWriter();
            out.append(res.toString());

        }
    }

    @Override
    public void destroy() {

    }
}